// routes/streamRoute.js
const OpenAI = require("openai");
const express = require('express');
const router = express.Router();

const openai = new OpenAI({
    baseURL: 'https://api.deepseek.com',
    apiKey: 'sk-f6884c0f138248a19e8a9869da52952c',
    dangerouslyAllowBrowser: true 
});

// 流式处理器独立为中间件
async function handleWordStreamRequest(req, res) {
    const { message } = req.body;
    console.log("【接收到的问题】", message);
    
    try {
        // 设置流式响应头
        res.writeHead(200, {
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Access-Control-Allow-Origin': '*'
        });

        // 创建流式响应
        const completion = await openai.chat.completions.create({
            messages: [{ 
                role: "system", 
                content: "给我描述列举单词"+message+"常见用法，回答末尾不用带互动性言语" 
            }],
            model: "deepseek-chat",
            stream: true
        });

        // 逐块发送数据
        for await (const chunk of completion) {
            const content = chunk.choices[0]?.delta?.content || '';
            console.log('【流式数据】',content);
            res.write(`${content}`); // SSE格式
        }
        
    } catch (err) {
        console.error('【请求出错】', err);
        res.write(`event: error\ndata: ${JSON.stringify({ error: true })}\n\n`);
    } finally {
        res.end(); // 确保连接关闭
    }
}

async function getChatStreamRequest(req, res) {
    const { message } = req.body;
    console.log("【接收到的问题】", message);
    
    try {
        // 设置流式响应头
        res.writeHead(200, {
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Access-Control-Allow-Origin': '*'
        });

        // 创建流式响应
        const completion = await openai.chat.completions.create({
            messages: [{ 
                role: "system", 
                content: message 
            }],
            model: "deepseek-chat",
            stream: true
        });

        // 逐块发送数据
        for await (const chunk of completion) {
            const content = chunk.choices[0]?.delta?.content || '';
            console.log('【流式数据】',content);
            res.write(`${content}`); // SSE格式
        }
        
    } catch (err) {
        console.error('【请求出错】', err);
        res.write(`event: error\ndata: ${JSON.stringify({ error: true })}\n\n`);
    } finally {
        res.end(); // 确保连接关闭
    }
}

async function getImage(req, res) {
    const { message, } = req.body;
    console.log("【接收到的问题】", message);
    
    try {
        // 设置流式响应头
        res.writeHead(200, {
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Access-Control-Allow-Origin': '*'
        })
    } catch (err) {
        console.error('【请求出错】', err);
        res.write(`event: error\ndata: ${JSON.stringify({ error: true })}\n\n`);
    } finally {
        res.end(); // 确保连接关闭
    }
}

// 正确的中间件挂载方式
router.post('/streamConsult', express.json(), handleWordStreamRequest); // 添加JSON解析中间件
router.post('/getChatStreamRequest', express.json(), getChatStreamRequest); // 添加JSON解析中间件
router.post('/getImage', express.json(), getImage); // 添加JSON解析中间件

module.exports = router; // 导出标准的Express Router实例